<?php
declare (strict_types = 1);

namespace app\controller;


use app\common\model\Headimgurl;
use QL\QueryList;
use Curl\Curl;
use think\facade\Request;
use think\facade\View;

class AdminHeadimgurls extends AdminInit
{
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if(Request::isAjax()){
            $d = \request()->param();

            $path = $d["nicknames"];

            //以 / 开头 不以 / 结尾
            if(substr($path,0,1) != "/"){
                return json(["code"=>400,"msg"=>"请以 / 开头"]);
            }
            if(substr($path,strlen($path) - 1,1) == "/"){
                return json(["code"=>400,"msg"=>"结尾不能有 / "]);
            }

            $path = ".".$d["nicknames"];
            //p($path);die;

            // 获取某目录下所有文件、目录名（不包括子目录下文件、目录名）
            $handler = opendir($path);
            while (($filename = readdir($handler)) !== false)
            {
                // 务必使用!==，防止目录下出现类似文件名“0”等情况
                if ($filename !== "." && $filename !== "..")
                {
                    $files[] = $filename ;
                }
            }

            closedir($handler);
            // 打印所有文件名
            $success = 0;
            $error = 0;
            foreach ($files as  $value) {
                $temp["headimgurl"] = $d["nicknames"].'/'.$value;

                if(Headimgurl::where("headimgurl",$temp["headimgurl"])->find()){
                    $error ++;
                }else{
                    $res = Headimgurl::create($temp);
                    $success ++;
                }
            }
            return json(["code"=>200,"msg"=>"导入成功{$success}条，失败{$error}条"]);
        }
        return  view();
    }

    public function curl_download_headimgurl()
    {
        if(\request()->isAjax()){
            $url = \request()->param("url",'',"trim");
            $type = \request()->param("type","","trim");

            if($type == 'gethtml'){
                //采集地址返回图片的数组
                $ql = QueryList::get($url);

                $rules = [
                    'img' => ['img','src']
                ];
                $data = $ql
                    ->range("#gui_left")
                    ->rules($rules)
                    ->find('img')
                    ->attrs('src');
                return json(["code"=>200,"msg"=>"成功","data"=>$data->all()]);
            }
            //downloadimg
            if($type == 'downloadimg'){
                //下载图片
                $date = date("Ymd");
                $path = "/data/download/{$date}";
                if(!is_dir(".".$path)){
                    mkdir(".".$path,0755);
                }
                $curl = new Curl();
                //Curl::setHeaders($headers);
                $curl->setHeader('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
                $curl->setHeader('Accept-Encoding','gzip, deflate');
                $curl->setHeader('Accept-Language','zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2');
                $curl->setHeader('Host','www.ik123.com');
                $curl->setHeader('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0');
                $curl->setHeader('Accept-Language','zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2');
                $curl->setHeader('Referer','http://www.ik123.com/q/qqtouxiang/nvsheng/');
                $curl->setHeader('Connection','keep-alive');
                $curl->setHeader('Cookie','UM_distinctid=176df86589ca0f-077af8c8b065bc8-4c302c7d-1fa400-176df86589e93f; CNZZDATA4422697=cnzz_eid%3D594675530-1610062533-null%26ntime%3D1610084737; bdshare_firstime=1610067892454; Hm_lvt_3179288820164e1ba15cf5b42a7fab62=1610067892; Hm_lpvt_3179288820164e1ba15cf5b42a7fab62=1610087736');
                $curl->setHeader('Upgrade-Insecure-Requests',1);
                $curl->setHeader('If-Modified-Since','Wed, 30 Dec 2020 07:15:23 GMT');
                $curl->setHeader('If-None-Match','W/"a9d0578a7bded61:0"');
                $curl->setHeader('Cache-Control','max-age=0');

                $curl->download($url, ".".$path.'/'.uniqid().".png");
                $img = $path.'/'.uniqid().".png";
                $mod = new Headimgurl();
                $res = $mod->save(["headimgurl"=>$img]);
                // Manual clean up.
                $curl->close();
                if($res){
                    return json(["code"=>200,"msg"=>"成功","data"=>$img]);
                }else{
                    return json(["code"=>400,"msg"=>"成功","data"=>$img]);
                }

            }

        }
        View::assign("nav",'');
        return  view();


    }

}
